﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PersonalFinanceManager.Repositories.Repositories;
using System.Drawing;
using System.Linq.Expressions;
using System.Data.Objects.SqlClient;

namespace PersonalFinanceManager.Website
{
    public partial class TransactionTypes : System.Web.UI.Page
    {
        TransactionsRepository transactionsRepo = new TransactionsRepository();
        int sessionUserID;

        protected void Page_Load(object sender, EventArgs e)
        {
            sessionUserID = 1; // Convert.ToInt32(Session["UserID"]);

            if (!IsPostBack)
            {
                ResetForm(true, "");
                txtSearchDateFrom.Text = String.Format("{0:dd.MM.yyyy}", DateTime.Now.Date.AddMonths(-1));
                txtSearchDateTo.Text = String.Format("{0:dd.MM.yyyy}", DateTime.Now.Date);

                for (int i = 0; i <= 23; i++)
                {
                    string s = String.Format("{0:00}", i);
                    ddlHour.Items.Add(new ListItem(s, s));
                }
                for (int i = 0; i < 60; i += 15)
                {
                    string s = String.Format("{0:00}", i);
                    ddlMinute.Items.Add(new ListItem(s, s));
                }
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            IList<DataModel.Transactions> transactions;
            DateTime searchDateFrom = Convert.ToDateTime(txtSearchDateFrom.Text).Date;
            DateTime searchDateTo = Convert.ToDateTime(txtSearchDateTo.Text).Add(new TimeSpan(23, 59, 59));

            string s = txtSearch.Text;
            Expression<Func<DataModel.Transactions, bool>> whereCondition = (x => (x.Name.Contains(s) || x.Description.Contains(s))
                                                                            && (x.DateOfTransaction >= searchDateFrom && x.DateOfTransaction <= searchDateTo)
                                                                             );
            transactions = transactionsRepo.FindAll(whereCondition, (x => x.DateOfTransaction), Repositories.SortingMode.descending);

            gvTransactions.DataSource = transactions;
            gvTransactions.DataBind();


            lblTotalCount.Text = transactions.Count.ToString();
            lblTotalDateFrom.Text = String.Format("{0:dd.MM.yyyy}", searchDateFrom);
            lblTotalDateTo.Text = String.Format("{0:dd.MM.yyyy}", searchDateTo);
            lblTotalMoney.Text = String.Format("{0:0.00} ден.", transactions.Sum(x => x.Money));

            txtName.Focus();
        }

        protected void gvTransactions_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = Convert.ToInt32(e.Keys["ID"]);
            DataModel.Transactions transaction = new DataModel.Transactions();
            transaction.ID = id;

            transactionsRepo.Delete(transaction);
        }

        protected void gvTransactions_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(gvTransactions.DataKeys[gvTransactions.SelectedIndex]["ID"]);
            DataModel.Transactions transaction = transactionsRepo.GetSingle(x => x.ID == id);
            ViewState["ID"] = transaction.ID;

            txtName.Text = transaction.Name;
            txtMoney.Text = String.Format("{0:0}", Math.Round(transaction.Money));
            txtDateOfTransaction.Text = String.Format("{0:dd.MM.yyyy}", transaction.DateOfTransaction.Date);
            ddlHour.SelectedValue = String.Format("{0:00}", transaction.DateOfTransaction.Hour);
            ddlMinute.SelectedValue = String.Format("{0:00}", transaction.DateOfTransaction.Minute);
            txtDescription.Text = transaction.Description;

            ResetForm(false, transaction.Name);
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            DataModel.Transactions transaction = new DataModel.Transactions();
            transaction.UserID = sessionUserID;
            transaction.Name = txtName.Text;
            transaction.Money = Convert.ToDecimal(txtMoney.Text);
            transaction.DateOfTransaction = Convert.ToDateTime(txtDateOfTransaction.Text).AddHours(Convert.ToInt32(ddlHour.SelectedValue)).AddMinutes(Convert.ToInt32(ddlMinute.SelectedValue));
            transaction.Description = txtDescription.Text;
            
            transactionsRepo.Insert(transaction);

            ResetForm(true, "");
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(ViewState["ID"]);
            DataModel.Transactions transaction = transactionsRepo.GetSingle(x => x.ID == id);
            transaction.Name = txtName.Text;
            transaction.Money = Convert.ToDecimal(txtMoney.Text);
            transaction.DateOfTransaction = Convert.ToDateTime(txtDateOfTransaction.Text).AddHours(Convert.ToInt32(ddlHour.SelectedValue)).AddMinutes(Convert.ToInt32(ddlMinute.SelectedValue));
            transaction.Description = txtDescription.Text;

            transactionsRepo.Update(transaction);

            ResetForm(true, "");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ResetForm(true, "");
        }

        protected void ResetForm(bool isInsert, string transactionname)
        {
            if (isInsert)
            {
                foreach (Control c in pnlTransactions.Controls)
                    if (c is TextBox)
                        (c as TextBox).Text = "";

                btnInsert.Visible = true;
                btnUpdate.Visible = false;
                pnlTransactions.GroupingText = "Внеси трансакција";
                pnlTransactions.DefaultButton = "btnInsert";
                txtDateOfTransaction.Text = String.Format("{0:dd.MM.yyyy}", DateTime.Now.Date);
            }
            else
            {
                btnInsert.Visible = false;
                btnUpdate.Visible = true;
                pnlTransactions.GroupingText = "Промени трансакција " + transactionname;
                pnlTransactions.DefaultButton = "btnUpdate";
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
        }

        protected void btnResetSearch_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
        }
    }
}